home *** CD-ROM | disk | FTP | other *** search
- Path: howland.reston.ans.net!gatech!clientlink!usenet
- From: Matthew Raffel <raffelm@netcom.com>
- Newsgroups: comp.lang.c
- Subject: Re: allocating unlimited string input....HELP
- Date: 10 Jan 1996 13:13:48 GMT
- Organization: ClientLink Corp.
- Message-ID: <4d0e2c$4uq@clientlink.com>
- NNTP-Posting-Host: 199.250.228.30
-
- ryangall@gpu.srv.ualberta.ca (Bobby Sixkiller) writes:
-
- A few things I may consider note worthy:
-
- You need test B for a vailidity as a pointer.
- EG:
- if (!B)
- printf("\nMalloc Failed");
-
- Additionally, you are never freeing B before "realloc"ing
- it. What is happening here, B gets set to point to
- some hunk of memory, then gets pointed to another hunk
- and another and so on. The pieces of memory B pointed to
- a one point is never released back to the system. This could
- be the cause of the failure after a fixed point, especially
- if you are compiling in a small or compact memory model.
-
- You can avoid "needing" A by using realloc which
- will preserve the contents of the memory.
-
- Below is a "rewrite" of your code to implement my thoughts.
- One, note, I did not compile it so...look out :=)
-
- int read(char *S)
- {
- char *B = NULL;
- char ch,count=0;
- int iCounter = 0;
-
-
- /* create an initial size */
- B = malloc(6);
-
- ch=getc(stdin);
-
- while(ch!='\n')
- {
- /* only realloc every so often...increment memory size by 5 bytes each time
- if (iCount == 5)
- {
- B=(char *) relloc(B, count + 5);
- iCount = 0;
- }
- else
- iCount ++;
-
- if (!b)
- {
- printf("\nB does not exist");
- break;
- }
- else
- {
- sprintf(B,"%s%c",B,ch);
-
- printf("%s---%i----%i\n",B,strlen(B),count);
- }
- ch=getc(stdin);
- count=count+1;
- }
-
- /* copy results to return value */
- if (S && B)
- strcpy(S, B);
-
- }
-
-
-
-